<?php

namespace Admin\Pages;

/**
 * Description of Index
 *
 * @author nofear
 */
class ProductForm extends Page {

    private $entityNamespace = 'Shared\Main\Product';
    private $entity = '\Shared\Main\Product';

    public function index($id = null) {
        $this->view = new \System\Template('@admin/productForm.twig');
        $id = $this->sanitize($id, $type = 'int');

        if ($id) {
            $Object = $this->EntityManager->find($this->entityNamespace, $id);

            if (!$Object) {
                $this->createNotFound('Няма такъв продукт.', 500);
            }
        } else {
            $Object = new $this->entity;
        }

        $Session = $this->getSession();
        if ($Session->have('message')) {
            $this->view->message = $Session->getMessage();
            $Session->removeMessage();
        }

        $this->view->form = new \Admin\Forms\Product($Object);
    }

    public function save() {
        $Saver = new \Admin\Savers\Saver();
        $request = $this->getRequest();
        $id = $this->sanitize($request->get('id'));
        $name = $this->sanitize($request->get('name'));
        $description = $this->sanitize($request->get('description'));
        $categoryId = (int) $request->get('categoryId');
        $inStock = (int) $request->get('inStock');
        
        if (
                $name && $categoryId
        ) {
            if ($id) {
                $Product = $this->EntityManager->find($this->entityNamespace, $id);

                if (!$Product) {
                    $this->createNotFound('Такъв домейн не съществува.');
                }
            } else {
                $Product = new \Shared\Main\Product();
            }

            $Metadata = $Saver->saveMetadata($Product);
            
            $Product->setName($name);
            $Product->setInStock($inStock);
            $Product->setMetadata($Metadata);
            $Product->setDescription($description);

            try {
                $Category = $this->EntityManager->find('Shared\Main\Category', $categoryId);
                $Product->setCategory($Category);
                $Saver->process($Product);
                $Saver->saveMultimedia($Product);
                $Saver->commit();

                $message['text'] = 'Промените са запазени успешно.';
                $message['type'] = 'alert-success';

                if (!$Product->getUrl()) {
                    $url = \Shared\URLManager::getInstance()->createPath('product', array('category' => 'test', 'slug' => 'name', 'id' => $Product->getId()));
                    $url = str_replace('/app_dev.php', '', $url);
                    $Product->setUrl($url);

                    $Saver->process($Product);
                    $Saver->commit();
                }
            } catch (\Exception $Ex) {
                $message['text'] = 'Възникна грешка, моля опитайте отново.';
                $message['type'] = 'alert-danger';
            }

            $path = \Shared\URLManager::getInstance()->createPath('admin_products_edit', array('id' => $id ? : $Product->getId()));
        } else {
            $message['text'] = 'Моля въведете име на домейна.';
            $message['type'] = 'alert-danger';

            $path = $this->getRequest()->headers->get('referer');
        }

        $Session = $this->getSession();
        $Session->setMessage($message);

        $this->redirect($path);
    }

    public function delete($id) {
        $id = $this->sanitize($id);
        $Session = $this->getSession();

        $message['text'] = 'Възникна грешка!';
        $message['type'] = 'alert-danger';

        if ($id) {
            $Product = $this->EntityManager->find($this->entityNamespace, $id);

            if ($Product) {
                $this->EntityManager->remove($Product);
                $this->EntityManager->flush();

                $message['text'] = 'Домейнът е изтрит успешно.';
                $message['type'] = 'alert-success';
            }
        }

        $Session->setMessage($message);
        $this->redirect(\Shared\URLManager::getInstance()->createPath('admin_products'));
    }

}
